package com.md.notes.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.core.content.ContextCompat;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.md.notes.R;
import com.md.notes.model.db.service.DaoService;
import com.md.notes.model.entity.Note;
import com.md.notes.model.module.file.FileMgrModel;
import com.md.notes.model.module.log.LoggerABC;
import com.md.notes.model.module.log.LoggerBuilder;
import com.md.notes.model.module.socket.FileSender;
import com.md.notes.model.module.socket.NetworkUtils;
import com.md.notes.model.module.socket.SocketServer;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SetFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SetFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private Button btnSyncNotes;
    private Button btnShowFirstNote;
    private Button btnSyncFile;//Socket启动发送文件
    private Button btnSocketServer;//Socket Server启动接收文件
    private EditText urlEditText;
    private EditText syncPathText;
    private TextView serverAddressView;
    private FileSender fileSender;
    private SocketServer socketServer;
    private boolean isServerRunning = false;

    private DaoService daoService;
    private ExecutorService executorService;

    public SetFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SetFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SetFragment newInstance(String param1, String param2) {
        SetFragment fragment = new SetFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        daoService = new DaoService(getContext());
        executorService = Executors.newSingleThreadExecutor(); // 初始化线程池
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_set, container, false);

        initView(view);
        initData();
        addListener();

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 确保在Fragment销毁时停止SocketServer
        if (isServerRunning && socketServer != null) {
            socketServer.stop();
            isServerRunning = false;
        }
        // 关闭线程池
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }

    private void initView(View view) {
        btnSyncNotes = view.findViewById(R.id.btnSyncNotes);
        btnShowFirstNote = view.findViewById(R.id.btnShowFirstNote);
        btnSyncFile = view.findViewById(R.id.btnSyncFile);
        btnSocketServer = view.findViewById(R.id.btnSocketServer);
        urlEditText = view.findViewById(R.id.UrlEditText);
        serverAddressView = view.findViewById(R.id.ServerAddressView);
        syncPathText = view.findViewById(R.id.SyncPathText);
    }

    private void initData() {
        fileSender = new FileSender();
        socketServer = new SocketServer();
        fileSender.setProgressListener(new FileSender.ProgressListener() {
            @Override
            public void onTotalFiles(int total) {
                Message message = mHandler.obtainMessage(0);
                Bundle bundle = new Bundle();
                bundle.putInt("TotalFiles",total);
                message.setData(bundle);
                mHandler.sendMessage(message);
            }

            @Override
            public void onFileProgress(String filename, long transferred, long total) {
                //updateProgressBar((int) (transferred * 100 / total));
            }

            @Override
            public void onComplete() {
                Message message = mHandler.obtainMessage(1);
                mHandler.sendMessage(message);
            }

            @Override
            public void onError(String message) {
                showErrorAlert(message);
            }
        });


    }

    private void addListener() {
        btnSyncNotes.setOnClickListener(v -> syncNotes());
        btnShowFirstNote.setOnClickListener(v -> showFirstNote());
        btnSyncFile.setOnClickListener(v->syncFiles());
        btnSocketServer.setOnClickListener(v->socketServerManager());
    }

    //Socket启动发送文件
    private void syncFiles() {
        String url = urlEditText.getText().toString();
        String[] ipPortArr = url.split(":");
        final String syncPath = syncPathText.getText().toString();
        executorService.execute(() -> {
            final LoggerABC loggerABC = LoggerBuilder.build(requireActivity());
            final String[] result = new String[1]; // 使用数组来存储结果
            try {
                // 获取外部存储根目录
                File rootDir = Environment.getExternalStorageDirectory();
                // 连接到服务器，假设服务器IP为"192.168.1.1"，端口为12345
                File folder = new File(rootDir, syncPath);
                fileSender.sendFolder(ipPortArr[0], Integer.parseInt(ipPortArr[1]), folder);
            } catch (Exception e) {
                e.printStackTrace();
                loggerABC.setException(e);
                loggerABC.logMessage(LoggerABC.ERROR,"Error occurred during syncFiles: " + e.getMessage());
                result[0] = "同步失败: " + e.getMessage(); // 修改数组中的值
            } finally {
            }

            // 在主线程中更新UI
            //requireActivity().runOnUiThread(() -> Toast.makeText(getContext(), result[0], Toast.LENGTH_SHORT).show());
        });
    }

    private void syncNotes(){
        FileMgrModel fileMgrModel = new FileMgrModel();
        List<Note> list = fileMgrModel.getNoteList();
        
        // 先清除所有旧数据
        daoService.clearAllNotes();
        
        // 插入新数据
        for (int i = 0; i < list.size(); i++) {
            daoService.insertNote(list.get(i));
        }
        Toast.makeText(getContext(), "同步完成", Toast.LENGTH_SHORT).show();
    }
    /**
     * 显示第一条笔记信息
     */
    private void showFirstNote() {
        Note note = daoService.getFirstNote();
        if (note != null) {
            String message = "标题: " + note.getTitle() + "\n"
                    + "创建日期: " + note.getCreateDate() + "\n"
                    + "规格号: " + note.getSpecNo() + "\n"
                    + "应用号: " + note.getAppNo() + "\n"
                    + "内容: " + note.getContent();

            new AlertDialog.Builder(getContext())
                    .setTitle("笔记信息")
                    .setMessage(message)
                    .setPositiveButton("确定", null)
                    .show();
        } else {
            new AlertDialog.Builder(getContext())
                    .setTitle("提示")
                    .setMessage("暂无笔记数据")
                    .setPositiveButton("确定", null)
                    .show();
        }
    }

    private void showErrorAlert(String message) {
        new AlertDialog.Builder(getContext())
                .setTitle("提示")
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }
    // Handler定义为类成员变量
    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                FragmentActivity activity = requireActivity();
                Bundle bundle = msg.getData();
                Toast.makeText(activity, "总文件数: " + bundle.getInt("TotalFiles"), Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 1) {
                FragmentActivity activity = requireActivity();
                Toast.makeText(activity, "同步完成", Toast.LENGTH_SHORT).show();
            }
            // 设置按钮为红色 - 服务器启动
            if (msg.what == 2) {
                btnSocketServer.setBackgroundColor(Color.RED);
                String ipAddress = NetworkUtils.getDeviceIpAddress(requireActivity());
                serverAddressView.setText("本机地址："+ipAddress+":3000");
                Toast.makeText(requireActivity(), "文件接收服务器已启动\nIP地址: " + ipAddress + "\n端口: 3000", Toast.LENGTH_LONG).show();
            }
            // 设置按钮为绿色 - 服务器停止
            if (msg.what == 3) {
                btnSocketServer.setBackgroundColor(Color.GREEN);
                Toast.makeText(requireActivity(), "文件接收服务器已停止", Toast.LENGTH_SHORT).show();
            }
            // 服务器启动失败
            if (msg.what == 4) {
                btnSocketServer.setBackgroundColor(Color.GREEN);
                Bundle bundle = msg.getData();
                Toast.makeText(requireActivity(), "服务器启动失败: " + bundle.getString("error"), Toast.LENGTH_SHORT).show();
            }
        }
    };

    private void socketServerManager(){
        if (!isServerRunning) {
            // 启动服务器 - 通过Handler设置按钮颜色
            isServerRunning = true;
            
            // 发送消息到Handler设置按钮为红色
            mHandler.sendEmptyMessage(2);
            
            //2. 开始新线程，调用Socket Server start方法
            executorService.execute(() -> {
                try {
                    socketServer.start();
                } catch (Exception e) {
                    e.printStackTrace();
                    // 发送消息到Handler处理启动失败
                    Message message = mHandler.obtainMessage(4);
                    Bundle bundle = new Bundle();
                    bundle.putString("error", e.getMessage());
                    message.setData(bundle);
                    mHandler.sendMessage(message);
                    isServerRunning = false;
                }
            });
        } else {
            // 停止服务器 - 通过Handler设置按钮颜色
            isServerRunning = false;
            // 发送消息到Handler设置按钮为绿色
            mHandler.sendEmptyMessage(3);
            
            executorService.execute(() -> {
                socketServer.stop();
                // 发送消息到Handler设置按钮为绿色
                mHandler.sendEmptyMessage(3);
            });
        }
    }
}